from pathlib import Path
from typing import Union

from qtpy.QtCore import QUrl
from qtpy.QtGui import QDesktopServices


def open_file_or_url(path: Union[str, Path]):
    """在默认应用程序中打开一个文件 或 URL."""
    if isinstance(path, str):
        if path.startswith('http'):
            QDesktopServices.openUrl(QUrl(str(path)))
        else:
            QDesktopServices.openUrl(QUrl.fromLocalFile(path))
    else:
        QDesktopServices.openUrl(QUrl.fromLocalFile(str(path)))


def get_readable_size(size: int):
    units = ["B", "KB", "MB", "GB", "TB", "PB"]
    unit_index = 0
    k = 1024.0
    while size >= k:
        size = size / k
        unit_index += 1
        if unit_index == len(units) - 1:
            break
    return "%.2f %s" % (size, units[unit_index])
